package com.grad.why.studentsystem.controller;

import com.grad.why.studentsystem.domain.Camera;
import com.grad.why.studentsystem.domain.FaceImgPath;
import com.grad.why.studentsystem.domain.Unknownfaces;
import com.grad.why.studentsystem.service.*;
import com.grad.why.studentsystem.util.Util;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/studentManageSystem")
public class UnKnownFacesController {
    @Autowired
    private UnKnownFacesService unKnownFacesService;

    @Autowired
    private OptionparamsService optionparamsService;

    @Autowired
    private FaceInfoService faceInfoService;

    @Autowired
    private CameraService cameraService;

    @Autowired
    private StudentService studentService;


    @RequestMapping("/getUnKnownFaces")
    @ResponseBody
    public Object getStudentList(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            HttpServletRequest request
    ) {
        try {
            HttpSession session = request.getSession();
            int type = (int) session.getAttribute("type");
            int bindid = (int)session.getAttribute("bindid");
            List<Unknownfaces> rows = null;
            long total = 0;

            if(type == 1){
                rows = unKnownFacesService.getUnknownFacesListByAdmin(offset, limit,search);
                total = unKnownFacesService.getUnknownFacesLengthByAdmin(search);
            }else if(type == 2){
                rows = unKnownFacesService.getUnknownFacesListByTeacher(offset,limit,search,bindid);
                total = unKnownFacesService.getUnknownFacesLengthByTeacher(search,bindid);
            }else if(type == 3){
                rows = unKnownFacesService.getUnknownFacesListByOrgStudent(offset,limit,search,bindid);
                total = unKnownFacesService.getUnknownFacesLengthByOrgStudent(search,bindid);
            }
            Map<String, Object> result = new HashMap<>(2);
            result.put("rows", rows);
            result.put("total", total);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/deleteUnknownFacesInfo/{ids}")
    @ResponseBody
    public String deleteUnknownFacesInfo(@PathVariable("ids") String ids){
        try{
            String[] idArray = ids.split("_");
            for(String id : idArray){
                int n = unKnownFacesService.deleteUnknownFaceInfoById(id);
                if(n<=0){
                    return null;
                }
            }
            return "OK";
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/checkSidMatchCid")
    @ResponseBody
    public String checkSidMatchCid(String sid,String courseId,String imgPath){
        try{
            if(Util.checkStrIsNumber(sid)){
                Integer formatterNum = Integer.parseInt(sid);
                int n = unKnownFacesService.checkSidMatchCourseId(formatterNum,Integer.parseInt(courseId));
                if(n <= 0){
                    return "该学号并没有选择该课程,请重试!";
                }else{
                    imgPath = imgPath.replace("/UnknownFaces","D:/unknowsFaces");
                    File file  = new File(imgPath);
                    String fileName = file.getAbsolutePath();
                    if(fileName.indexOf("\\") != -1){
                        fileName = fileName.substring(fileName.lastIndexOf("\\"));
                    }
                    String rootPath = optionparamsService.getParamValueByParamName("imgRootPath");
                    String filePath = rootPath+sid;
                    File targetFile = new File(filePath);

                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }

                    File[] files = targetFile.listFiles();
                    int maxId = -1;
                    for(int i = 0;i<files.length;i++){
                        File f = files[i];
                        String s = f.getName();
                        s = s.split("\\.")[0];
                        s = s.split("_")[1];
                        if(Integer.parseInt(s)>maxId){
                            maxId = Integer.parseInt(s);
                        }
                    }

                    maxId = maxId + 1;
                    FileOutputStream out = null;
                    try {
                        String rimg = "";
                        if(fileName.contains(".jpg")){
                            out = new FileOutputStream(filePath+"/"+sid+"_"+maxId+".jpg");
                            rimg = "/Path/"+sid+"/"+sid+"_"+maxId+".jpg";
                        }else if(fileName.contains(".jpge")){
                            out = new FileOutputStream(filePath+"/"+sid+"_"+maxId+".jpge");
                            rimg = "/Path/"+sid+"/"+sid+"_"+maxId+".jpge";
                        }else if(fileName.contains(".png")){
                            out = new FileOutputStream(filePath+"/"+sid+"_"+maxId+".png");
                            rimg = "/Path/"+sid+"/"+sid+"_"+maxId+".png";
                        }else if(fileName.contains(".JPG")){
                            out = new FileOutputStream(filePath+"/"+sid+"_"+maxId+".jpg");
                            rimg = "/Path/"+sid+"/"+sid+"_"+maxId+".jpg";
                        }else if(fileName.contains(".JPGE")){
                            out = new FileOutputStream(filePath+"/"+sid+"_"+maxId+".jpge");
                            rimg = "/Path/"+sid+"/"+sid+"_"+maxId+".jpge";
                        }else if(fileName.contains(".PNG")){
                            out = new FileOutputStream(filePath+"/"+sid+"_"+maxId+".png");
                            rimg = "/Path/"+sid+"/"+sid+"_"+maxId+".png";
                        }

                        if(rimg.equals("")){
                            return null;
                        }

                        FileUtils.copyFile(file,out);
                        out.flush();
                        out.close();

                        //需传入的参数
                        String a = filePath+"/"+sid+"_"+maxId;
                        if(fileName.contains(".jpg")){
                            a = a + ".jpg";
                        }else if(fileName.contains(".jpge")){
                            a = a + ".jpge";
                        }else if(fileName.contains(".png")){
                            a = a + ".png";
                        }else if(fileName.contains(".JPG")){
                            a = a + ".jpg";
                        }else if(fileName.contains(".JPGE")){
                            a = a + ".jpge";
                        }else if(fileName.contains(".PNG")){
                            a = a + ".png";
                        }
                        //设置命令行传入参数
                        String[] args = new String[] { "python", "D:\\git\\face_recognition-master\\face_recognition-master\\mytest\\testByImage.py", a};
                        Process pr = Runtime.getRuntime().exec(args);
                        BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                        String line;
                        boolean flag = true;
                        while ((line = in.readLine()) != null) {
                            if(Integer.parseInt(line) > 0){
                                Integer maxDataId = faceInfoService.getMaxId() + 1;
                                FaceImgPath faceImgPath = new FaceImgPath();
                                faceImgPath.setFid(maxDataId);
                                faceImgPath.setPath(rimg);
                                faceImgPath.setSid(Integer.parseInt(sid));
                                int rows = faceInfoService.addFaceInfoBySidAndFacePath(faceImgPath);

                                //加入到人脸特征集
                                if(rows>0){
                                    List<Camera> cameraList = cameraService.getRunningCameraInfos();
                                    for(int i = 0;i<cameraList.size();i++){
                                        Camera camera = cameraList.get(i);
                                        camera.setShouldupdate(1);
                                        cameraService.updateCameraInfo(camera);
                                    }
                                    in.close();
                                    pr.waitFor();
                                    return rimg;
                                }else{
                                    flag = false;
                                    break;
                                }
                            }else{
                                flag = false;
                                if(fileName.contains(".jpg")){
                                    File delFile = new File(filePath+"/"+sid+"_"+maxId+".jpg");
                                    delFile.delete();
                                }else if(fileName.contains(".jpge")){
                                    File delFile = new File(filePath+"/"+sid+"_"+maxId+".jpge");
                                    delFile.delete();
                                }else if(fileName.contains(".png")){
                                    File delFile = new File(filePath+"/"+sid+"_"+maxId+".png");
                                    delFile.delete();
                                }else if(fileName.contains(".JPG")){
                                    File delFile = new File(filePath+"/"+sid+"_"+maxId+".jpg");
                                    delFile.delete();
                                }else if(fileName.contains(".JPGE")){
                                    File delFile = new File(filePath+"/"+sid+"_"+maxId+".jpge");
                                    delFile.delete();
                                }else if(fileName.contains(".PNG")){
                                    File delFile = new File(filePath+"/"+sid+"_"+maxId+".png");
                                    delFile.delete();
                                }
                                break;
                            }
                        }

                        in.close();
                        pr.waitFor();
                        if(flag == true){
                            List<Camera> cameraList = cameraService.getRunningCameraInfos();
                            for(int i = 0;i<cameraList.size();i++){
                                Camera camera = cameraList.get(i);
                                camera.setShouldupdate(1);
                                cameraService.updateCameraInfo(camera);
                            }
                            return rimg;
                        }else{
                            return null;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            }else{
                return "请填写正确的学号信息";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/modifyUnknownFaceInfo")
    @ResponseBody
    public String modifyUnknownFaceInfo(String unknownfaceid,String imgPath,String sid){
        try{
            Unknownfaces unknownfaces = unKnownFacesService.getUnknownFaceInfoById(unknownfaceid);
            unknownfaces.setSid(Integer.parseInt(sid));
            unknownfaces.setSname(studentService.getStudentNameBySid(Integer.parseInt(sid)));
            unknownfaces.setCheckstate(1);
            imgPath = imgPath.replace("/UnknownFaces","D:/unknowsFaces");
            File file = new File(imgPath);
            boolean flag = file.delete();
            if(!flag){
                return null;
            }else{
                int n = unKnownFacesService.updateInfoByEntity(unknownfaces);
                if(n <= 0){
                    return null;
                }
            }
            return "OK";
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
